/*
 * @features: 主要功能
 * @description: 内容说明
 * @Date: 2021-09-28 10:11:30
 * @Author: judu233(769471424@qq.com)
 * @LastEditTime: 2022-08-22 00:45:48
 * @LastEditors: judu233
 */

import SqlUtil from "../../Storage/SqlUtil";
import { ExtendsLoad } from "../CCExtends";

/**扩展原型组件 */
@ExtendsLoad(Map)
export class MapBaseExtends {

}
/**扩展组件实例方法 */
@ExtendsLoad(Map.prototype)
export class MapExtends {

    /**
     * 存储当前数组里的元素
     * @param saveStr 要保存的key
     */
    static saveMap(saveStr: string) {
        let map = this as any as Map<any, any>;
        return SqlUtil.setItem(saveStr, map.transArr());
    }

    /**
     * 从存储中加载指定字符的数据，并覆盖当前对应的元素
     * @param saveStr 要加载的key
     * @param def 默认值        
     * @param isClear 是否清理数组里的值，默认不清除
     * @returns 
     */
    static reloadMap(saveStr: string, def = new Map(), isClear = false) {
        try {
            let map = this as any as Map<any, any>;
            let getArr = SqlUtil.getItem(saveStr, def) as [any, any][];
            if (isClear) {
                map.clear();
            }
            map.addList(getArr);
            return true;
        } catch (error) {
            return false;
        }
    }
    /**
     * 把map转成value arr 
     * => [[value],[value]]
     * @returns []
     */
    static transValueArr<T>() {
        let map = this as any as Map<any, T>;
        return Array.from(map.values());
    }
    /** 
     * 把map转成key arr 
     * => [[key],[key]]
     * @returns []
     */
    static transKeyArr<K>() {
        let map = this as any as Map<K, any>;
        return Array.from(map.keys());
    }
    /** 
     * 把map转成arr 
     * => [[key,value],[key,value]]
     * @returns []
     */
    static transArr<K, V>() {
        let map = this as any as Map<K, V>;
        return Array.from(map.entries());
    }

    /**
     * 向map添加多个元素
     * @param arr map转换的arr
     */
    static addList(arr: [any, any][]) {
        let map = this as any as Map<any, any>;
        arr.forEach(elm => {
            map.set(elm[0], elm[1]);
        })
    }

}